package com.sheepych.water_clock;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sheepych
 */
@Slf4j
@Service
public class SendWaterMsgService {
    private static final String KEY = "e5e256f0-9d58-4c31-9df0-9faa9547cd88";
    private static final String URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";
    private static final String START_TIME = "09:00";
    private static final String END_TIME = "21:00";
    private static final String REMINDER_MESSAGE = """
                **💦💧健康饮水提醒 💧** \s
               ⏰ **当前时间**: %s \s
               🔔 **下次提醒**: %s \s
               🕘 **工作时间段**: 9:00～12:00，13:30～18:00 \s
               📊 **今日进度**: %s \s
              \s
               > 🌟 **温馨提示** \s
               > 1️⃣ 建议小口慢饮，每次200ml左右 \s
               > 2️⃣ 避免一次性大量饮水 \s
               > 3️⃣ 最佳水温为25-37℃ \s
            """;


    public void sendMsg() {
        // Constants
        try {
            String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
            if (!isWithinTimeRange(nowTime)) {
                //打印提醒
                log.info("当前时间不在提醒范围内【{}-{}】，跳过提醒", START_TIME, END_TIME);
                return;
            }
            String nextTime = LocalDateTime.now().plusMinutes(30)
                    .format(DateTimeFormatter.ofPattern("HH:mm"));

            Map<String, Object> paramMap = new HashMap<>(16);
            paramMap.put("msgtype", "markdown");
            Map<String, String> content = new HashMap<>(16);
            content.put("content", String.format(REMINDER_MESSAGE, nowTime, nextTime, calculateProgress()));
            paramMap.put("markdown", content);

            // Send request
            String url = URL + KEY;
            String body = JSONUtil.toJsonStr(paramMap);
            log.info("发送消息到企业微信: {}, 内容: {}", url, body);
            HttpUtil.post(url, body);
        } catch (Exception e) {
            log.error("发送消息到企业微信异常: {}", e.getMessage(), e);
        }
    }

    private boolean isWithinTimeRange(String currentTime) {
        try {
            LocalTime now = LocalTime.parse(currentTime);
            LocalTime start = LocalTime.parse(START_TIME);
            LocalTime end = LocalTime.parse(END_TIME);
            return !now.isBefore(start) && !now.isAfter(end);
        } catch (DateTimeParseException e) {
            log.error("时间比较出现异常: {}", e.getMessage(), e);
            return false;
        }
    }

    private String calculateProgress() {
        LocalTime now = LocalTime.now();
        LocalTime morningStart = LocalTime.of(9, 0);
        LocalTime morningEnd = LocalTime.of(12, 0);
        LocalTime afternoonStart = LocalTime.of(13, 30);
        LocalTime afternoonEnd = LocalTime.of(18, 0);

        // 计算总工作时间（分钟）
        long totalMinutes = Duration.between(morningStart, morningEnd).toMinutes() +
                Duration.between(afternoonStart, afternoonEnd).toMinutes();

        // 计算已工作时间（分钟）
        long workedMinutes = 0;
        if (now.isAfter(morningStart)) {
            workedMinutes += Duration.between(morningStart, now.isBefore(morningEnd) ? now : morningEnd).toMinutes();
        }
        if (now.isAfter(afternoonStart)) {
            workedMinutes += Duration.between(afternoonStart, now.isBefore(afternoonEnd) ? now : afternoonEnd).toMinutes();
        }

        double percentage = Math.min(100, workedMinutes * 100.0 / totalMinutes);
        return String.format("%.2f%%", percentage);
    }

}
